import { MCPClient } from './mcpClient.js';
import { AIProvider } from './aiProvider.js';
import { ConversationManager } from './conversationManager.js';
import { readFileSync } from 'fs';
import { createInterface } from 'readline';
import chalk from 'chalk';

class MCPClientApp {
  constructor() {
    this.config = JSON.parse(readFileSync('./config.json', 'utf8'));
    this.mcpClient = new MCPClient(this.config.mcp_servers, this.config.client_settings);
    this.aiProvider = new AIProvider(this.config.ai_models);
    this.conversationManager = new ConversationManager();
    this.rl = createInterface({
      input: process.stdin,
      output: process.stdout
    });
  }

  async initialize() {
    console.log(chalk.blue('🚀 正在初始化 MCP 客户端...'));
    
    try {
      // 连接 MCP 服务器
      await this.mcpClient.connectAll();
      console.log(chalk.green('✅ MCP 服务器连接成功!'));
      
      // 获取所有可用工具
      const tools = await this.mcpClient.getAllTools();
      console.log(chalk.cyan(`📋 已加载 ${tools.length} 个工具`));
      
      // 设置 AI 提供者的工具
      this.aiProvider.setTools(tools);
      
      console.log(chalk.green('✅ 初始化完成! 开始对话...'));
      console.log(chalk.yellow('💡 输入 "/help" 查看帮助, "/quit" 退出程序'));
      
    } catch (error) {
      console.error(chalk.red('❌ 初始化失败:'), error.message);
      process.exit(1);
    }
  }

  async handleUserInput(input) {
    if (input.startsWith('/')) {
      return this.handleCommand(input);
    }
    
    try {
      console.log(chalk.blue('🤖 AI 正在思考...'));
      
      // 获取对话历史
      const messages = this.conversationManager.getMessages();
      messages.push({ role: 'user', content: input });
      
      // 调用 AI 模型
      const response = await this.aiProvider.chat(messages);
      
      // 处理工具调用
      if (response.tool_calls && response.tool_calls.length > 0) {
        console.log(chalk.yellow('🔧 执行工具调用...'));
        
        for (const toolCall of response.tool_calls) {
          const result = await this.mcpClient.callTool(
            toolCall.function.name,
            JSON.parse(toolCall.function.arguments)
          );
          
          messages.push({
            role: 'tool',
            tool_call_id: toolCall.id,
            content: JSON.stringify(result)
          });
        }
        
        // 获取最终回复
        const finalResponse = await this.aiProvider.chat(messages);
        console.log(chalk.green('🤖 AI:'), finalResponse.content);
        
        // 保存对话
        this.conversationManager.addMessage('user', input);
        this.conversationManager.addMessage('assistant', finalResponse.content);
      } else {
        console.log(chalk.green('🤖 AI:'), response.content);
        
        // 保存对话
        this.conversationManager.addMessage('user', input);
        this.conversationManager.addMessage('assistant', response.content);
      }
      
    } catch (error) {
      console.error(chalk.red('❌ 处理失败:'), error.message);
    }
  }

  async handleCommand(command) {
    const [cmd, ...args] = command.slice(1).split(' ');
    
    switch (cmd) {
      case 'help':
        this.showHelp();
        break;
      case 'tools':
        await this.showTools();
        break;
      case 'servers':
        await this.showServers();
        break;
      case 'clear':
        this.conversationManager.clear();
        console.log(chalk.green('✅ 对话历史已清空'));
        break;
      case 'model':
        if (args[0]) {
          this.aiProvider.switchModel(args[0]);
          console.log(chalk.green(`✅ 已切换到模型: ${args[0]}`));
        } else {
          console.log(chalk.yellow('当前模型:'), this.aiProvider.getCurrentModel());
        }
        break;
      case 'quit':
        await this.cleanup();
        process.exit(0);
        break;
      default:
        console.log(chalk.red(`❌ 未知命令: ${cmd}`));
    }
  }

  showHelp() {
    console.log(chalk.cyan(`
📖 MCP Client 帮助
==================
/help     - 显示此帮助
/tools    - 显示所有可用工具
/servers  - 显示服务器状态
/clear    - 清空对话历史
/model    - 显示当前模型
/model <name> - 切换模型
/quit     - 退出程序

💡 直接输入消息开始与 AI 对话
`));
  }

  async showTools() {
    const tools = await this.mcpClient.getAllTools();
    console.log(chalk.cyan('\n🛠️ 可用工具:'));
    tools.forEach(tool => {
      console.log(chalk.white(`  • ${tool.name}`), chalk.gray(`- ${tool.description}`));
    });
  }

  async showServers() {
    const servers = this.mcpClient.getServerStatus();
    console.log(chalk.cyan('\n🖥️ 服务器状态:'));
    servers.forEach(server => {
      const status = server.connected ? chalk.green('✅ 已连接') : chalk.red('❌ 未连接');
      console.log(chalk.white(`  • ${server.name}`), status, chalk.gray(`- ${server.description}`));
    });
  }

  async start() {
    await this.initialize();
    
    const askQuestion = () => {
      this.rl.question(chalk.blue('\n💬 您: '), async (input) => {
        if (input.trim()) {
          await this.handleUserInput(input.trim());
        }
        askQuestion();
      });
    };
    
    askQuestion();
  }

  async cleanup() {
    console.log(chalk.yellow('🧹 正在清理资源...'));
    await this.mcpClient.disconnectAll();
    this.rl.close();
    console.log(chalk.green('✅ 再见!'));
  }
}

// 启动应用
const app = new MCPClientApp();

// 处理优雅关闭
process.on('SIGINT', async () => {
  await app.cleanup();
  process.exit(0);
});

process.on('SIGTERM', async () => {
  await app.cleanup();
  process.exit(0);
});

app.start().catch(console.error);